/* eslint-disable import/no-extraneous-dependencies */
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineChunkWebpackPlugin = require('html-webpack-inline-chunk-plugin');

// postcss plugins
const postcssImporter = require('postcss-import');
const postcssOpacity = require('postcss-opacity');
const autoprefixer = require('autoprefixer');

const isProd = process.env.NODE_ENV === 'production'; // 判断打包环境

// chunkhash为当前页的哈希值
// hash为整站的哈希值
module.exports = {
  entry: {
    vendor: ['vue'],
    app: './src/js/main.js',
  },

  output: {
    path: './dist',
    publicPath: isProd ? '//cdn.dreamhiway.com/v2/myj' : 'http://localhost:8080/',
    filename: isProd ? 'js/[name].[chunkhash].js' : 'js/[name].js',
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: isProd ? 'babel-loader' : 'babel-loader!eslint-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        loader: (isProd ?
          ExtractTextPlugin.extract('css-loader?sourceMap!postcss-loader') :
          'style-loader!css-loader?sourceMap!postcss-loader'),
        exclude: /node_modules/,
      },
      {
        test: /\.(png|jpg|gif)$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: 'img/[name].[ext]?[hash:7]',
        },
      },
    ],
  },

  devtool: isProd ? 'source-map' : 'eval-source-map',

  devServer: {
    stats: {
      colors: true,
      chunks: false,
    },
    historyApiFallback: true, // 懒加载
    // proxy: {
    //   '*': {
    //     target: 'http://192.168.2.21:8085',
    //     secure: false,
    //     /* eslint-disable consistent-return */
    //     bypass(req) {
    //       if (req.url.includes('.')) {
    //         return req.url;
    //       }
    //     },
    //     /* eslint-enable consistent-return */
    //   },
    // }, // 代理
  },

  plugins: [
    new webpack.DefinePlugin({
      DREAMHIWAY_HOST: JSON.stringify(isProd ? '//www.dreamhiway.com/' : '//192.168.2.21:8085/'),
    }),
    // 内敛样式和js
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
    // 提取公共代码，manifest为webpack运行时的代码
    new webpack.optimize.CommonsChunkPlugin({
      name: ['vendor', 'manifest'],
    }),
  ].concat(isProd ? [
    new ExtractTextPlugin('css/[name].css'),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
    }),
    // 上线时内敛
    new InlineChunkWebpackPlugin({
      inlineChunks: ['manifest'],
    }),
  ] : [
    new webpack.NoErrorsPlugin(),
  ]),

  postcss(webpack) {
    return [
      postcssImporter({
        addDependencyTo: webpack,
      }),
      postcssOpacity(),
      autoprefixer(),
    ];
  },
};
